# This file is part of MaixPY
# Copyright (c) sipeed.com
#
# Licensed under the MIT license:
#   http://www.opensource.org/licenses/mit-license.php
#
# Send image(jpeg) to server and display on server(PC),


from network_esp32 import wifi
import socket, image, sensor, lcd, time, uos


lcd.init(freq=15000000)
lcd.draw_string(5, 50, "steel surface defect detection system", lcd.WHITE, lcd.BLACK)
lcd.draw_string(100, 100, "start self-dect", lcd.WHITE, lcd.BLACK)
time.sleep(1)
lcd.clear()


try:  # 摄像头初始化与自检
    sensor.reset()
    sensor.set_pixformat(sensor.RGB565)
    sensor.set_framesize(sensor.QVGA)
    sensor.run(1)
    sensor.skip_frames()
    lcd.display(sensor.snapshot())
    lcd.draw_string(100, 100, "Camera init successfully", lcd.WHITE, lcd.BLACK)
    time.sleep(1)
except Exception as e:
    lcd.draw_string(100, 100, "Camera init FAIL", lcd.RED, lcd.BLACK)
    print("Sensor Camera error:", e)
    time.sleep(1)
lcd.clear()


SERVER = ("172.20.10.3", 8888)  # 服务器地址， 端口
SSID = "Kearney"  # WiFi
PASW = "asdcxz321.."


"""连接 wifi，直到连接成功为止"""
lcd.draw_string(100, 100, "connecting to wifi...", lcd.WHITE, lcd.BLACK)
while not wifi.isconnected():
    try:
        # Running within 3 seconds of power-up can cause an SD load error
        # wifi.reset(is_hard=False)
        wifi.reset(is_hard=True)
        print("WiFi connecting")
        wifi.connect(SSID, PASW)
        if wifi.isconnected():
            print("WiFi connected")
            break
    except Exception as e:
        print(e)
        continue
print("network state:", wifi.ifconfig())
lcd.clear()
lcd.draw_string(100, 100, "connected to wifi", lcd.WHITE, lcd.BLACK)
time.sleep(1)
lcd.clear()

lcd.draw_string(5, 100, "start to send photo to server", lcd.WHITE, lcd.BLACK)
time.sleep(1)
lcd.clear()
sock = socket.socket()
try:
    print("socket connecting")
    sock.connect(SERVER)
    print("socket connected")
    # sock.settimeout(0) # time in seconds

    lcd.init()
    for i in uos.listdir("/sd/images"):  # 遍历图像
        print(i)
        imgPath = "/sd/images/" + i
        img = image.Image(imgPath, copy_to_fb=True)  # 从 sd 卡读取 jpg
        # lcd.display(img)  # 屏幕显示图像，暂时隐藏，不然会立马覆盖上一轮显示出来的检测结果

        f = open(imgPath, "rb")
        while True:
            img = f.read(2048)
            time.sleep_ms(10)  # 不延迟一下容易丢包
            if not img or (len(img) == 0):
                print("send end")
                break
            sock.send(img)
            time.sleep_ms(10)  # 不延迟一下容易丢包
        f.close()

        lines = sock.recv(1024).decode("utf-8").split("\n")  # 接收检测结果
        print(lines)
        img = image.Image(imgPath, copy_to_fb=True)
        for line in lines:
            nxywh = line.split(" ")
            img.draw_string(
                int(nxywh[1]), int(nxywh[2]), nxywh[0], color=(255, 0, 0)
            )  # 在图像上绘制分类名称，红色字体
            img.draw_rectangle(
                int(nxywh[1]),
                int(nxywh[2]),
                int(nxywh[3]),
                int(nxywh[4]),
                color=(255, 0, 0),
                thickness=2,
            )  # 在图像上绘制框框，红色，线宽2
        lcd.display(img)  # 屏幕显示最终图像
except Exception as e:
    print("socket connect error:", e)
    lcd.draw_string(100, 100, "Socket connect ERROR", lcd.RED, lcd.BLACK)
    time.sleep(1)
    lcd.clear()
finally:
    sock.close()
    print("socket closed")
